<?php

namespace app\admin\server;
use app\admin\model\Cate as CateModel;
use app\admin\validate\CateValidate;
use think\Cache;

class Cate
{


	/**
	 * 获取商品分类
	 * @return [type] [description]
	 */
	public function getCatesByWhere($where = [])
	{
		//获取提交数据
		$param = input('param.');
		//每页条数
        $limit = $param['pageSize'];
        $offset = ($param['pageNumber'] - 1) * $limit;
        //商品名查询
        if (!empty($param['searchText'])) {
            $where['cate_name'] = ['like', '%' . $param['searchText'] . '%'];
        }else{
        	$where['pid'] = $param['pid'];
        }
        //获取商品列表
		$cates = CateModel::where($where)->order("sort asc")->limit($offset,$limit)->select();
		return $this->getNewResult($cates);
	}


	/**
	 * 添加或修改
	 * @return [type] [description]
	 */
	public function save()
	{
		//获取提交数据
		$params = input('post.');
		$id = isset($params['id']) ? $params['id'] : '';
		//修改
		$cateValidate = new CateValidate();
		if(!$cateValidate->batch()->check($params)){
			//错误信息 
			$errorInfo = $ProductValidate->getError();
			$errorInfo = is_array($errorInfo) ? array_values($errorInfo)[0] : $errorInfo;
			return msg(-1,'',$errorInfo);
		}
		//
		$cateModel = new CateModel();
		//判断是添加还是修改
		try{
			if($id){
				//修改
				$result = $cateModel->save($params,['id'=>$id]);
				$meg = '修改';
			}else{
				//添加
				$params['add_time'] = time();
				$result = $cateModel->save($params);
				$meg = '提交';	
			}
			return msg(1, url('cate/lists'), $meg.'成功');
		}catch(PDOException $e){
			return msg(-2,'',$e->getMessage());
		}
		
	}


	public function delete()
	{
		$id = input('param.id');
		$cateModel = new CateModel();
		$count = $cateModel->where('pid',$id)->count();
		if($count > 0){
			return msg(-1,'','存在下级分类，不能删除');
		}
		try{
            $cateModel->where('id', $id)->delete();
            return msg(1, '', '删除成功');

        }catch(\Exception $e){
            return msg(-1, '', $e->getMessage());
        }
	}


		/**
	 * 上下架
	 */
	public function saveStatusByID()
	{
		$CateModel = new CateModel();
		$id = input('param.id');
		//查询status
		$status = CateModel::get($id)->is_show;

		$data['is_show'] = 1;
		if($status == 1){
		 	$data['is_show'] = 0;
		}
		try{
		 	$CateModel->save($data,['id'=>$id]);
		 	return msg(1, '', '操作成功');
		}catch(PDOException $e){
			return msg(-2, '', $e->getMessage());
		}
	}



	/**
	 * 获取所有分类
	 * @return [type] [description]
	 */
	public function getCateTree()
	{
		$catesModel = new CateModel();
		$cates = $catesModel->order("sort desc,id desc")->field("id,pid,cate_name")->select();
		if($cates){
			$cates = collection($cates)->toArray();
		}
		return $this->getTree($cates);
	}
	




    /**
     * 无限极递归分类
     * @param  array  $array 分类的数据
     * @param  int    $pid   父级id
     * @param  int $level   级别
     * @return array     绑定上下级的数据
     */
	public function getTree($array,$pid = 0,$level = 0)
	{
		//声明静态变量  接收数据  foreach完不至于被销毁
		static $lists = [];
		//遍历数组
		foreach($array as $key => $val)
		{
			//首次遍历，先找到pid = 0 的父级分类
			if($val['pid'] == $pid){
				$val['level'] = $level; /*设置级别*/
				//
				$val['cate_name'] = str_repeat('|--', $val['level']).$val['cate_name'];
				//开始递归 查询父级ID的下级分类
				//将找到的父级数据放入list中
				$lists[] = $val;
				//移出已经存放的数据
				unset($array[$key]);
				
				$this->getTree($array,$val['id'],$level+1);
			}
		}
		//输出格式
		return $lists;
	}




	/**
	 * 数据重组
	 */
	private function getNewResult($selectResult)
    {
        foreach($selectResult as $key=>$vo){
            $selectResult[$key]['pic'] = '<img src="' . $vo['pic'] . '" width="40px" height="40px">';
            $selectResult[$key]['childe'] = '<a href="/admin/cate/lists?pid='.$vo['id'].'">查看</a>';
            $selectResult[$key]['is_show'] = showOperate($this->isShow($vo['id'],$vo['is_show']));
            
            $selectResult[$key]['operate'] = showOperate($this->makeButton($vo['id']));
        }
        return $selectResult;
    }





    private function isShow($id,$is_show)
    {
    	if($is_show == 1){
            $button['不推荐'] = [
                'auth' => 'cate/is_show',
                'href' => "javascript:is_show(" . $id . ")",
                'btnStyle' => 'danger',
                'icon' => 'fa fa-long-arrow-down'
            ];
        }else{
             $button['推荐'] = [
                'auth' => 'cate/is_show',
                'href' => "javascript:is_show(" . $id . ")",
                'btnStyle' => 'primary',
                'icon' => 'fa fa-long-arrow-up'
            ];
        }
        return $button;
    }

	/**
     * 拼装操作按钮
     * @param $id
     * @return array
     */
    private  function makeButton($id)
    {
        $button = [
            '编辑' => [
                'auth' => 'cate/update',
                'href' => url('cate/update', ['id' => $id]),
                'btnStyle' => 'primary',
                'icon' => 'fa fa-paste'
            ],
            '删除' => [ 
                'auth' => 'cate/del',
                'href' => "javascript:del(" . $id . ")",
                'btnStyle' => 'danger',
                'icon' => 'fa fa-trash-o'
            ],
            
   
        ];

        return $button;
    }
}